<template>
  <div class="image-preview" v-if="src" :style="imageSize">
    <div class="image-wrapper">
      <el-image :src="src" class="image" :class="imageClass" />
      <div class="menu">
        <i class="el-icon-delete" @click="handleImageRemove"></i>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    src: {
      type: String,
      required: true
    },
    imageClass: {
      type: String
    }
  },
  data() {
    return {
      height: 200,
      width: 150
    };
  },
  methods: {
    handleImageRemove() {
      this.$confirm("确认删除该图片?", "提示", {
        confirmButtonText: "删除",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$emit("remove");
        })
        .catch(() => {});
    }
  },
  computed: {
    sizeRatio() {
      return this.width / this.height;
    },
    imageSize() {
      let r = this.sizeRatio;
      let w = this.width;
      let h = this.height;
      if (w == h) {
        w = h = 140;
      } else if (w > h) {
        if (r >= 3) {
          w = 140;
          h = 47;
        } else {
          w = 140;
          h = 140 / r;
        }
      } else if (w < h) {
        let r2 = h / w;
        if (r2 >= 3) {
          h = 140;
          w = 47;
        } else {
          h = 140;
          w = 140 / r2;
        }
      }
      return {
        width: `${w}px`,
        height: `${h}px`
      };
    }
  },
  watch: {
    src: {
      immediate: true,
      handler(v) {
        if (v) {
          const hash = new URL(v).hash.slice(1);
          const [width, height] = hash.split("x");
          width && (this.width = parseFloat(width));
          height && (this.height = parseFloat(height));
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/mixin.scss";

.image-preview {
  .image-wrapper {
    position: relative;
    display: inline-block;
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.3);
    font-size: 0;
    height: 100%;
    .image {
      height: 100%;
    }

    .menu {
      position: absolute;
      left: 0;
      top: 0;
      bottom: 0;
      right: 0;
      @include flex-align-center(flex);
      justify-content: space-around;

      color: #fff;
      background: rgba(0, 0, 0, 0.5);
      pointer-events: none;
      transition: all 0.3s;
      opacity: 0;
      font-size: 20px;
      i {
        cursor: pointer;
      }
    }
    &:hover {
      .menu {
        opacity: 1;
        pointer-events: all;
      }
    }
  }
}
</style>
